#include "widget.h"

#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    mEdit->setMinimumWidth(240);
    mBtnSelect->setMaximumWidth(45);

    connect(mBtnSelect, &QPushButton::clicked, [this] {
        QString path = QFileDialog::getOpenFileName();
        if(path.isEmpty())
            return;
        mEdit->setText(path);
    });
    connect(mBtnFix, &QPushButton::clicked, [this] {
        QString filePath = mEdit->text();
        QFileInfo info(filePath);
        if(!info.isFile()) {
            QMessageBox::critical(this, "错误", "无效的文件路径");
            return;
        }

        //创建临时文件夹
        QDir appDir(APP_DIR);
        if(appDir.exists("tmp")) {
            if(!removeDirectory(APP_DIR + "/tmp")) {
                QMessageBox::critical(this, "错误", "清除残留临时文件失败");
                return;
            }
        }
        appDir.mkdir("tmp");

        //解压文件
        QStringList list = JlCompress::extractDir(filePath, APP_DIR + "/tmp");
        if(QDir(APP_DIR + "/tmp").isEmpty()) {
            QMessageBox::critical(this, "错误", "不支持的格式");
            return;
        }

        //移除custom.xml
        QDir(APP_DIR + "/tmp/docProps").remove("custom.xml");

        //压缩文件
        QString fileName = info.completeBaseName() + "_fix." + info.suffix();
        QDir dir(info.path());
        int i = 2;
        while(dir.exists(fileName)) {
            fileName = info.completeBaseName() + "_fix" + QString::number(i) + "." + info.suffix();
            i++;
        }
        if(!JlCompress::compressDir(info.path() + "/" + fileName, APP_DIR + "/tmp")) {
            QMessageBox::critical(this, "错误", "压缩失败");
            return;
        }

        if(!removeDirectory(APP_DIR + "/tmp"))
            QMessageBox::warning(this, "提示", "未能成功清除临时文件");
        QMessageBox::information(this, "提示", "完成");
    });

    QHBoxLayout *layMain = new QHBoxLayout;
    layMain->setSpacing(0);
    layMain->addWidget(mEdit);
    layMain->addWidget(mBtnSelect);
    layMain->addSpacing(15);
    layMain->addWidget(mBtnFix);
    setLayout(layMain);

    adjustSize();
    setMinimumHeight(height());
    setMaximumHeight(height());
}

Widget::~Widget()
{

}

bool Widget::removeDirectory(const QString &path) {
    QDir qdir(path);
    QStringList files = qdir.entryList(QDir::Files);
    QStringList dirs = qdir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    bool succeed = true;
    for(const QString &file : files)
        if(!qdir.remove(file))
            succeed = false;
    for(const QString &dir : dirs)
        if(!removeDirectory(path + "/" + dir))
            succeed = false;
    if(!qdir.rmdir("."))
        succeed = false;
    return succeed;
}
